package com.srwl.mytx.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.content.res.ResourcesCompat;

import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.srwl.mytx.Constant;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.R;
import com.srwl.mytx.domain.MyFile;
import com.srwl.mytx.domain.Statement;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by wei on 2016/6/2.
 */
public class Utils {

    private static final String TAG = "Utils";

    public static void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) MyApplication.getInstance().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static void showKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) MyApplication.getInstance().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    public static boolean isKeyBoardShowing(Activity mActivity) {

        //获取当前屏幕内容的高度
        int screenHeight = mActivity.getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);

        return screenHeight - rect.bottom - getSoftButtonsBarHeight(mActivity) != 0;

    }

    /**
     * 底部虚拟按键栏的高度
     *
     * @return
     */

    public static int getSoftButtonsBarHeight(Activity mActivity) {
        DisplayMetrics metrics = new DisplayMetrics();
        //这个方法获取可能不是真实屏幕的高度
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        //获取当前屏幕的真实高度
        mActivity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight) {
            return realHeight - usableHeight;
        } else {
            return 0;
        }
    }


    public static String numberFormat(Number price) {
        if (price == null) {
            return "0";
        }
        if (price.doubleValue() >= 10000) {
            DecimalFormat df = new DecimalFormat("0.00");

            double nomalPrice = price.doubleValue() / 10000;
            return df.format(nomalPrice) + "万";
        } else {
            return price + "";
        }
    }

    public static String numberFormat2(Number number) {
        if (number == null) {
            return "0";
        }
        if (number.doubleValue() >= 1000) {
            DecimalFormat df = new DecimalFormat("0.00");

            double nomalPrice = number.doubleValue() / 1000;
            return df.format(nomalPrice) + "k";
        } else {
            return number + "";
        }
    }

    //只检测 是否是11位的数字，具体格式是否正确，在服务端检测
    public static boolean checkMobileNum(String phoneNumber) {

        Pattern p = Pattern.compile("^1\\d{10}$");
        Matcher m = p.matcher(phoneNumber);
        return m.matches();
    }

    /**
     * 通过正则判断是否是手机号
     *
     * @param mobiles
     * @return
     */
    @Deprecated
    public static boolean isPhoneNumber(String mobiles) {


        Pattern p = Pattern.compile("^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static void editViewValueErrorAnimate(final View view, final Context context) {
        view.setBackground(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tx_edit_text_bg_value_empty, null));
        ViewAnimator.animate(view).translationX(0, 15, -15, 15, -15, 15, -10, 5, 0).duration(1000)
                .onStop(new AnimationListener.Stop() {
                    @Override
                    public void onStop() {
                        view.setBackground(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tx_bg_et, null));
                    }
                })
                .start();
    }

    public static void viewValueEmptyAnimate(final View view) {
        ViewAnimator.animate(view).translationX(0, 15, -15, 15, -15, 15, -10, 5, 0).duration(1000).start();
    }

    public static RequestBody toRequestBody(String value) {

        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
        return requestBody;

    }

    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    // 替换、过滤特殊字符
    public static String stringFilter(String str) throws PatternSyntaxException {
        if (str == null) {
            return "";
        }
        str = str.replaceAll("【", "[").replaceAll("】", "]").replaceAll("！", "!");//替换中文标号
        String regEx = "[『』]"; // 清除掉特殊字符
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }


    public static int dpToPx(int dp, Context context) {
        return (int) (context.getResources().getDisplayMetrics().density * dp + 0.5f);

    }

    public static int pxToDp(int px, Context context) {

        return (int) (px / context.getResources().getDisplayMetrics().density + 0.5f);
    }

    /**
     * 保留两位小数，小数后面的只舍不入
     *
     * @param number
     * @return
     */
    public static String moneyFormat(Object number) {
        if (number == null) {
            return "0.00";
        }
        DecimalFormat format = new DecimalFormat("###,###0.00");
        format.setRoundingMode(RoundingMode.FLOOR);
        String amount = format.format(number);
        //如果有小数点，并且结尾是 0的情况下，清除掉一个0
//        if (amount.contains(".") && amount.endsWith("0")) {
//            amount = amount.substring(0, amount.length() - 1);
//        }
        return amount;
    }

    public static double moneyFormatStringToDouble(String moneyString) {

        DecimalFormat format = new DecimalFormat("###,###0.00");
        format.setRoundingMode(RoundingMode.FLOOR);
        try {
            Number parse = format.parse(moneyString);
            if (parse != null) {
                return parse.doubleValue();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return 0;
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 判断字符串是否为URL
     *
     * @param urls 用户头像key
     * @return true:是URL、false:不是URL
     */
    public static boolean isHttpUrl(String urls) {
        String regex = "(((https|http)?://)?([a-z0-9]+[.])|(www.))" + "\\w+[.|\\/]([a-z0-9]{0,})?[[.]([a-z0-9]{0,})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z0-9]{0,}+|/?)";
        //设置正则表达式
        Pattern pat = Pattern.compile(regex.trim());
        Matcher mat = pat.matcher(urls.trim());
        return mat.matches();
    }

    public static boolean isSendMessage(Message message) {
        return TextUtils.equals(message.getFromId(), UserProfileManager.getInstance().getLoginUserInfo().getuId());
    }

    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        return mNetworkInfo != null && mNetworkInfo.isConnected();
    }


    /**
     * 判断是否是游客
     *
     * @return
     */
    public static boolean isTempUser(User user) {
        if (user == null || user.getType() == null) {
            return false;
        }
        return Constant.USER_TYPE_TEMP == user.getType();
    }

    /**
     * 不使用压缩策略
     *
     * @param myFile
     * @return
     */
    public static String getIconUrl(MyFile myFile) {

        return getIconUrl(myFile, "");
    }

    /**
     * 按缩放50%策略生成远程地址
     *
     * @param myFile
     * @return
     */
    public static String getIconUrlScale50(MyFile myFile) {

        return getIconUrl(myFile, "?x-oss-process=style/icon_50");
    }

    private static String getIconUrl(MyFile myFile, String style) {
        if (myFile == null) {
            return "";
        }
        String iconUrl;

        //默认视频一定含有封面图片
        if (myFile.getType() == MyFile.FILE_TYPE_VIDEO) {
            String videoCover = myFile.getVideoCover();
            iconUrl = AliOssService.TOPIC_IMAGE_PRE_URL + videoCover + style;
            return iconUrl;
        }
        iconUrl = AliOssService.TOPIC_IMAGE_PRE_URL + myFile.getUrl() + style;

        return iconUrl;

    }

    /**
     * 根据主题
     * 获取用于显示到图标上的
     * 远程图片或者视频地址
     *
     * @param targetTopic
     * @return
     */
    public static String getIconUrlScale20(Topic targetTopic) {

        return getCoverUrl(targetTopic, "?x-oss-process=style/icon_20");//使用缩小到20%的策略

    }

    public static String getTopicListPreviewUrl(Topic topic) {
        return getCoverUrl(topic, "?x-oss-process=style/icon_50");//使用缩小到50%的策略
    }

    /**
     * 优先返回图片地址
     * 因为图片可以使用缩略策略
     *
     * @param targetTopic
     * @param style
     * @return
     */
    public static String getCoverUrl(Topic targetTopic, String style) {
        if (targetTopic == null) {
            return "";
        }
        String iconUrl = "";

        //如果有封面，优先返回封面，没有封面，优先返回图片
        String videoCover = targetTopic.getVideoCover();
        if (!TextUtils.isEmpty(videoCover)) {
            iconUrl = AliOssService.TOPIC_IMAGE_PRE_URL + videoCover + style;
            return iconUrl;
        }
        List<String> pictures = targetTopic.getPictures();
        if (pictures != null && pictures.size() != 0 && !pictures.get(0).equals("")) {
            String topicIconUrl = pictures.get(0);
            if (topicIconUrl != null && topicIconUrl.startsWith("http")) {
                iconUrl = topicIconUrl;
            } else {
                iconUrl = AliOssService.TOPIC_IMAGE_PRE_URL + topicIconUrl + style;
            }
        } else if (!TextUtils.isEmpty(targetTopic.getVideo())) {
            String topicIconUrl = targetTopic.getVideo();
            if (topicIconUrl != null && topicIconUrl.startsWith("http")) {
                iconUrl = topicIconUrl;
            } else {
                iconUrl = AliOssService.TOPIC_VIDEO_PRE_URL + topicIconUrl;
            }
        }

        return iconUrl;
    }


    public static String getIconUrl(LiveRoom liveRoom) {
        String iconUrl = "";
        String video = liveRoom.getVideo();
        if (!TextUtils.isEmpty(video)) {
            if (video.startsWith("http")) {
                iconUrl = video;
            } else {
                iconUrl = AliOssService.TOPIC_VIDEO_PRE_URL + video;
            }
        } else {
            String cover = liveRoom.getCover();
            if (!TextUtils.isEmpty(cover)) {
                if (cover.startsWith("http")) {
                    iconUrl = cover;
                } else {
                    iconUrl = AliOssService.TOPIC_IMAGE_PRE_URL + cover + "?x-oss-process=style/icon_20";//使用图片处理策略，尺寸压缩到20%
                }
            }
        }
        return iconUrl;
    }

    /**
     * 流水图标远程地址获取
     * 优先显示图片
     *
     * @param statement
     * @return
     */
    public static String getIconUrl(Statement statement) {
        if (statement == null) {
            return "";
        }
        String iconUrl = "";
        String picture = statement.getPicture();

        if (!TextUtils.isEmpty(picture)) {
            if (picture.startsWith("http")) {
                iconUrl = picture;
            } else {
                iconUrl = AliOssService.TOPIC_IMAGE_PRE_URL + picture + "?x-oss-process=style/icon_20";
            }
        } else {
            String video = statement.getVideo();
            if (!TextUtils.isEmpty(video)) {
                if (video.startsWith("http")) {
                    iconUrl = video;
                } else {
                    iconUrl = AliOssService.TOPIC_VIDEO_PRE_URL + video;
                }
            }

        }
        return iconUrl;
    }


    /**
     * 用直播间列表显示
     * 使用尺寸压缩50%的处理策略
     *
     * @param liveRoom
     * @return
     */
    public static String getLiveRoomListAdapterUrl(LiveRoom liveRoom) {
        String iconUrl = "";
        String cover = liveRoom.getCover();
        if (!TextUtils.isEmpty(cover)) {
            if (cover.startsWith("http")) {
                iconUrl = cover;
            } else {
                iconUrl = AliOssService.TOPIC_IMAGE_PRE_URL + cover + "?x-oss-process=style/icon_50";//使用图片处理策略，尺寸压缩到50%
            }
        } else {
            String video = liveRoom.getVideo();
            if (video.startsWith("http")) {
                iconUrl = video;
            } else {
                iconUrl = AliOssService.TOPIC_VIDEO_PRE_URL + video;
            }
        }

        return iconUrl;
    }

    public static String getPictureUrlScale50(String url) {
        return getPictureUrl(url, "?x-oss-process=style/icon_50");
    }

    public static String getPictureUrl(String url, String style) {
        String remoteUrl;
        if (url != null && url.startsWith("http")) {
            remoteUrl = url;
        } else {
            remoteUrl = AliOssService.TOPIC_IMAGE_PRE_URL + url;
        }
        return remoteUrl;
    }

    public static List<String> generateTopicBottomDialogItems(Topic topic) {
        final Integer status = topic.getStatus();
        final Integer type = topic.getType();
        List<String> itemStrings = new ArrayList<>();
        if (status == null || type == null) {
            return itemStrings;
        }
        //地区 行业 学校 三个类型 暂时不支付删除，因为这3种类型可以接受捐赠，所以可以管理捐赠
        if (type == Constant.TOPIC_TYPE_AREA || type == Constant.TOPIC_TYPE_SCHOOL || type == Constant.TOPIC_TYPE_INDUSTRY) {
            //如果聊天室是未审核状态
            if (status == Constant.TOPIC_STATUS_WAIT_VERIFY) {
                itemStrings.add(Constant.BOTTOM_ITEM_NAME_DELETE);
                //如果聊天室未通过审核状态
            } else if (status == Constant.TOPIC_STATUS_VERIFY_FAIL) {
                itemStrings.add(Constant.BOTTOM_ITEM_NAME_DELETE);
            } else {
                itemStrings.add(Constant.BOTTOM_ITEM_NAME_MANAGE_DONATION);
                itemStrings.add(Constant.BOTTOM_ITEM_EXIT_MANAGER);
                itemStrings.add(Constant.BOTTOM_ITEM_SURRENDER_MANAGER);
            }
            //焦点类型也可以编辑，未通话审核的全部内容可编辑，通过审核的，标题和分类不能编辑
            itemStrings.add(Constant.BOTTOM_ITEM_NAME_EDIT);
        } else if (type == Constant.TOPIC_TYPE_REWARD) {

            //没有完结、没有取消的悬赏类型主题，才显示 编辑选项、撤回悬赏的选项
            if (status != Constant.TOPIC_STATUS_REWARD_CANCEL && status != Constant.TOPIC_STATUS_REWARD_COMPLETE) {
                itemStrings.add(Constant.BOTTOM_ITEM_NAME_EDIT);
                itemStrings.add(Constant.BOTTOM_ITEM_NAME_REVOKE_REWARD);
            }
            //当状态是取消或者是完成的时候，显示删除选项
            if (status == Constant.TOPIC_STATUS_REWARD_CANCEL || status == Constant.TOPIC_STATUS_REWARD_COMPLETE) {
                itemStrings.add(Constant.BOTTOM_ITEM_NAME_DELETE);
            }

        } else {//曝光类型主题，和已经不是正常悬赏状态的悬赏类型主题，显示删除选项
            itemStrings.add(Constant.BOTTOM_ITEM_NAME_EDIT);
            itemStrings.add(Constant.BOTTOM_ITEM_NAME_DELETE);
        }
        return itemStrings;
    }

}
